<?php
declare (strict_types = 1);

use \app\cms\community\thirdPartyApi\aliyun\OSS\OSSFileBase;
use \app\cms\community\thirdPartyApi\aliyun\lib\config;
use app\cms\model\buildModel;
use OSS\Core\OssException;
use think\db\ConnectionInterface;

if (!function_exists('getOssUrl')) {
    /**
     * 获取OSS 对象文件
     * @param string $bucket 桶
     * @param string $object 文件对象
     * @param int $config_id 配置id
     * @return iflow\Response
     * @throws OssException
     */
    function getOssUrl(string $bucket, string $object, int $config_id): iflow\Response {
        $url = (new OSSFileBase(
            new config($config_id)
        )) -> getSignUrl($bucket, $object, 3600 * 1000);
        if ($url === '') return message() -> nodata('暂无文件数据');
        return response() -> setRedirect($url) -> data($url);
    }
}

if (!function_exists('unzip')) {
    /**
     * 解压
     * @param string $zip
     * @param string $savePath
     * @return bool
     */
    function unzip(string $zip, string $savePath): bool {
        $unzip = new ZipArchive();
        if ($unzip -> open($zip)) {
            $unzip -> extractTo($savePath);
            $unzip -> close();
            return true;
        }
        return false;
    }
}

if (!function_exists('array_to_env')) {
    function array_to_env(array $data, $savePath = ''): string {
        $env = '';
        foreach ($data as $key => $value) {
            $env .= "[$key]";
            array_map(function ($value, $key) use (&$env) {
                if (is_string($value)) $env .= "{$key}={$value}";
            }, $value);
        }

        if ($savePath !== '') {
            // 将 env数据 存入指定文件
            $path = dirname($savePath);
            !is_dir($path) && mkdir($path, 0755, true);
            file_put_contents($savePath, $env);
        }
        return $env;
    }
}

if (!function_exists('load_sql_save_to_server')) {
    /**
     * 读取指定文件夹下sql 存入数据库
     * @param ConnectionInterface|buildModel $db
     * @param string $file
     * @return bool
     */
    function load_sql_save_to_server(ConnectionInterface|buildModel $db, string $file): bool {
        // 读取sql文件

        $fileList = find_files($file, function (\SplFileInfo $item) {
            return $item->getExtension() === 'sql';
        });

        foreach ($fileList as $file) {
            $path = str_replace("\\", "/", $file->getPathname());
            $sql = file_get_contents($path);

            $sql = str_replace("\r", "\n", $sql);
            $sql = explode(";\n", $sql);

            // 写入数据库
            foreach ($sql as $value) {
                $value = trim($value);
                if ($value !== '') $db -> execute($value);
            }
        }
        return true;
    }
}
